package com.briup.homework.chap10;



class Clerk{
    private int count;
    // 以同步方法的形式改变一下，这里的锁指的是this
    public synchronized void produceProduct(){
        String name = Thread.currentThread().getName();
        if(count<20){
            count++;
            System.out.println(name+"生产第"+count+"个包子");
            this.notifyAll();
        }else {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public synchronized void consumeProduct(){
        String name = Thread.currentThread().getName();
        if(count>0){
            count--;
            System.out.println("---------"+name+"正在消费第"+count+"个包子");
            notifyAll();
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
class Producer extends Thread{
    private Clerk clerk;
    public Producer(String name, Clerk clerk){
        super(name);
        this.clerk = clerk;
    }
    @Override
    public void run() {
        while(true){
            this.clerk.produceProduct();
        }
    }
}
class Consumer extends Thread{
    private Clerk clerk;
    public  Consumer(String name, Clerk clerk){
        super(name);
        this.clerk = clerk;
    }
    @Override
    public void run() {
        while(true){
            this.clerk.consumeProduct();
        }
    }
}

public class Test10_2_ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Thread t1 = new Producer("p1", clerk);
        Thread t2 = new Producer("p2", clerk);
        Thread t3 = new Consumer("c1", clerk);
        Thread t4 = new Consumer("c2", clerk);
        Thread t5 = new Consumer("c3", clerk);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}
